package xj.model.uml;

import static xj.model.uml.UMLModelConstants.ROLE_REGION;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class OrthogonalState extends State {

  public OrthogonalState() {
    this(null);
  }

  public OrthogonalState(String name) {
    super(name, StateType.Orthogonal_State);
  }

  public void addRegion(OrthogonalRegion s) {
    if (s != null) {
      regions.add(s);
      addOwnedElement(s, ROLE_REGION);
    }
  }

  public void removeRegion(OrthogonalRegion s) {
    if (s != null) {
      regions.remove(s);
      removeOwnedElement(s);
    }
  }

  public List<OrthogonalRegion> getRegions() {
    return regions;
  }

  public OrthogonalRegion getRegion(String name) {
    if (name != null) {
      Iterator<OrthogonalRegion> iter = regions.iterator();
      while (iter.hasNext()) {
	OrthogonalRegion s = iter.next();
	if (name.equals(s.getName())) {
	  return s;
	}
      }
    }
    return null;
  }

  public OrthogonalRegion getRegion(int i) {
    if (i >= 0 && i < regions.size()) {
      return regions.get(i);
    }
    return null;
  }

  public void makeRegions(int n) {
    regions.clear();
    if (n > 0) {
      for (int i = 0; i < n; i++) {
	addRegion(new OrthogonalRegion("#region" + (i + 1) + "#"));
      }
    }
  }

  public int numberOfRegions() {
    return regions.size();
  }

  // add state to region i
  public void addState(int i, State s) {
    // System.out.println("OrthogonalState.addState() i=" + i + " #regions="
    // + regions.size());
    if (i >= 0 && i < regions.size()) {
      OrthogonalRegion r = regions.get(i);
      if (r != null) {
	r.addState(s);
      }
    }
  }

  @Override
  public Object clone() throws CloneNotSupportedException {
    OrthogonalState os = (OrthogonalState) super.clone();

    os.regions = new ArrayList<OrthogonalRegion>();
    Iterator<OrthogonalRegion> iter = regions.iterator();
    while (iter.hasNext()) {
      OrthogonalRegion r = iter.next();
      os.addRegion((OrthogonalRegion) r.clone());
    }
    return os;
  }

  protected List<OrthogonalRegion> regions = new ArrayList<OrthogonalRegion>();

}
